package cate.game.train.favorability;

import cate.common.util.GameResult;
import cate.game.event.RoleEventPublisher;
import cate.game.event.hero.HeroPowerChangeEvent;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.bag.hero.Hero;
import cate.game.train.favorability.msg.ImproveFavorabilityResp;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

public class TrainFavorabilityHandler implements RoleEventPublisher {
    private GameResult<Hero> findHeroResult(Role role, String uid) {
        GameResult<Hero> r = new GameResult<>();
        if (StringUtils.isBlank(uid)) {
            return r.fail("英雄不存在！");
        }
        Hero hero = role.getBag().hero.getItem(uid);
        if (hero == null) {
            return r.fail("英雄不存在！");
        }
        r.data = hero;
        return r.success();
    }

    public GameResult<Void> improveFavorability(Role role, String heroUid, MixRes drugItems){
        GameResult<Void> gameResult = new GameResult<>();
        GameResult<Hero> heroResult = findHeroResult(role, heroUid);
        if (!heroResult.ok()) {
            return gameResult.fail(heroResult);
        }
        Hero hero = heroResult.data;
        EcResult<Void> takeResult = hero.improveFavorability(drugItems);
        if (!takeResult.ok()) {
            return gameResult.fail(takeResult);
        }
        role.sendNow(new ImproveFavorabilityResp(heroUid, hero.favorabilityOn));
        role.getBase().updatePower();
        publishEvent(role, new HeroPowerChangeEvent(hero.getRole(), hero));
        return gameResult;
    }
}
